package com.loop.unclelend.ui.fragment

import android.graphics.Color
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.View
import android.widget.SeekBar
import com.loop.unclelend.R
import com.loop.unclelend.databinding.UiPageLoanLimitBinding
import com.loop.unclelend.databinding.UncleIncludeLoanAmountBinding
import com.loop.unclelend.databinding.UncleIncludeLoanLimitSelectBinding
import com.loop.unclelend.databinding.UncleIncludeLoanUncreditedBinding
import com.loop.unclelend.pro.ProFragment
import com.loop.unclelend.ui.activity.Act_Apply
import com.loop.unclelend.ui.activity.Act_Steps
import com.loop.unclelend.ui.activity.Act_Steps_Wait
import com.loop.unclelend.ui.presenter.Pre_Loan_Limit
import com.loop.unclelend.ui.view.IView_Loan_Limit
import com.loop.unclelend.utils.BarUtil
import com.loop.unclelend.utils.dialog.Dialog_Guide
import com.loop.unclelend.utils.event.UncleEventData
import com.loop.unclelend.utils.helper.CustomConfigsHelper
import com.loop.unclelend.utils.helper.SharedHelper
import com.loop.unclelend.utils.log.UncleLog
import org.json.JSONObject
import java.math.BigDecimal

/**
 * UncleLend
 * @Author wwdeng
 * @CreateTime: 2024/9/10 10:32
 * @Annotation：未授信、未借款、已借款
 */
class Fm_Loan_Limit: ProFragment(), IView_Loan_Limit {
    lateinit var binding: UiPageLoanLimitBinding
    var presenter: Pre_Loan_Limit? = null

    override fun getUncleRootView(inflater: LayoutInflater): View {
        binding = UiPageLoanLimitBinding.inflate(inflater)
        return binding.root
    }

    override fun initUncleView() {
        rootViewBinding.layoutContainer.setBackgroundColor(Color.parseColor("#00000000"))

        initRefreshLayout()
    }

    override fun initUncleListener() {
    }

    override fun initUncleData() {
        if (presenter == null){
            presenter = Pre_Loan_Limit(this)
        }
        if (!getAct().isFinishing){
            showUncleLoading()
        }
        presenter!!.checkUncleProcessSteps()

        //APP配置接口数据
        val customData = CustomConfigsHelper.getUncleCustomData()
        if (customData != null){
            //总额度
            val amount = customData.optString("homeAmount","0")
            binding.txtAmount.text = amount

            //最低年利率
            val annualRate = customData.optString("maxAnnualRate")
            val showText = String.format(getString(R.string.loan_lowest_annual_rate),annualRate)
            val spString = SpannableString(showText)
            val startIndex = showText.indexOf(annualRate)
            spString.setSpan(ForegroundColorSpan(Color.parseColor("#FFF86F00")), startIndex, showText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
            binding.txtAnnualRate.text = spString
        }
    }

    /* 初始化刷新 */
    private fun initRefreshLayout() {
        //禁止加载
        binding.layoutRefresh.setEnableLoadMore(false)
        binding.layoutRefresh.setEnableAutoLoadMore(false)
        binding.layoutRefresh.setOnRefreshListener {
            getAct().publishEventData(UncleEventData(UncleEventData.TYPE.UNCLE_PROCESS_REFRESH))
        }
        binding.layoutRefresh.setOnLoadMoreListener {
            binding.layoutRefresh.finishLoadMore()
        }
    }

    /**
     * 未授信
     */
    override fun showUncleUncreditedViews() {
        binding.layoutMask.visibility = View.VISIBLE
        binding.layoutInclude.removeAllViews()
        val uncreditedBinding = UncleIncludeLoanUncreditedBinding.inflate(layoutInflater)
        uncreditedBinding.unlockLayout.setOnClickListener {
            presenter!!.checkUncleAllPermissionsAgree()
        }
        binding.layoutInclude.addView(uncreditedBinding.root)
    }

    /**
     * 未借款（选择借款额度）
     */
    override fun showUncleSelectAmountViews(data: JSONObject) {
        binding.layoutMask.visibility = View.GONE
        binding.layoutInclude.removeAllViews()
        val selectBinding = UncleIncludeLoanLimitSelectBinding.inflate(layoutInflater)

        //最小申请额度
        val minAmount = BigDecimal(data.optString("minAmount")).stripTrailingZeros().toPlainString().toInt()
        //最大申请额度
        val maxAmount = BigDecimal(data.optString("maxAmount")).stripTrailingZeros().toPlainString().toInt()
        //额度颗粒度
        val granularity = data.optInt("granularity")

        //设置最大值
        val maxProcess = (maxAmount - minAmount) / granularity
        selectBinding.seekBar.max = maxProcess
        //设置当前值
        selectBinding.seekBar.progress = 0

        selectBinding.txtMinAmount.text = minAmount.toString()
        selectBinding.txtMaxAmount.text = maxAmount.toString()
        selectBinding.txtAmount.text = minAmount.toString()

        selectBinding.seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                // 当进度改变时调用
                val showProcess = progress * granularity + minAmount
                selectBinding.txtAmount.text = "$showProcess"
            }
            override fun onStartTrackingTouch(seekBar: SeekBar?) {
            }
            override fun onStopTrackingTouch(seekBar: SeekBar?) {
            }
        })

        selectBinding.btnApply.setOnClickListener {
            presenter!!.checkUncleAllPermissionsAgree(selectBinding.txtAmount.text.toString())
        }
        binding.layoutInclude.addView(selectBinding.root)
        binding.txtAmount.text = maxAmount.toString()

        //是否显示过引导指引
        if (SharedHelper.getUncleSPBoolean(SharedHelper.UNCLE_SPKEY.UNCLE_DIALOG_GUIDE_SHOW)){
            selectBinding.seekBar.progress = maxProcess / 2
            binding.layoutInclude.post {
                val setY = selectBinding.seekBar.y + binding.layoutInclude.y + BarUtil.getStatusBarHeight() + selectBinding.seekBar.height / 2
                val guide = Dialog_Guide(context,setY,object : Dialog_Guide.IDialogCallback{
                    override fun onGuideDismiss() {
                        SharedHelper.saveUncleSPData(SharedHelper.UNCLE_SPKEY.UNCLE_DIALOG_GUIDE_SHOW,false)
                        //设置当前值
                        selectBinding.seekBar.progress = 0
                    }
                })
                guide.setCancelable(false)
                guide.setCanceledOnTouchOutside(false)
                guide.show()
            }
        }

    }

    /**
     * 已借款（显示剩余额度）
     */
    override fun showUncleAmountViews(data: JSONObject) {
        binding.layoutMask.visibility = View.GONE
        binding.layoutInclude.removeAllViews()
        val amountBinding = UncleIncludeLoanAmountBinding.inflate(layoutInflater)
        //已用额度
        val utilisedAmount = BigDecimal(data.optString("utilisedAmount")).stripTrailingZeros().toPlainString()
        amountBinding.txtUsedAmount.text = utilisedAmount
        amountBinding.txtUsedAmountTips.text = String.format(getString(R.string.loan_amount_in_use),utilisedAmount)
        //剩余可用额度
        val availableAmount = BigDecimal(data.optString("availableAmount")).stripTrailingZeros().toPlainString()
        amountBinding.txtAvailableAmount.text = availableAmount
        amountBinding.txtAvailableAmountTips.text = String.format(getString(R.string.loan_amount_available),availableAmount)
        //总额度 = 已用额度 + 剩余可用额度
        val totalAmount = utilisedAmount.toFloat() + availableAmount.toFloat()
        amountBinding.btnUse.isEnabled = true
        amountBinding.btnUse.setBackgroundResource(R.drawable.circle_fill_fff23a42)
        //可用额度 <= 0 不可点击去使用
        if (availableAmount.toInt() <= 0){
            amountBinding.btnUse.isEnabled = false
            amountBinding.btnUse.setBackgroundResource(R.drawable.circle_fill_ffcfcdd2)
        }

        //去借款
        amountBinding.btnUse.setOnClickListener {
            presenter!!.checkUncleAllPermissionsAgree(availableAmount)
        }

        //去还款
        amountBinding.btnRepay.setOnClickListener {
            publishEventData(UncleEventData(UncleEventData.TYPE.UNCLE_SHOW_REPAY))
        }

        binding.layoutInclude.addView(amountBinding.root)
        binding.txtAmount.text = BigDecimal(totalAmount.toString()).stripTrailingZeros().toPlainString()
    }

    /**
     * 进入认证流程
     */
    override fun showUncleStepsPage() {
        onIntent(Act_Steps::class.java)
    }

    /**
     * 进入申贷页面
     */
    override fun showUncleLoanApplyPage(amount: String) {
        Act_Apply.start(requireContext(),amount)
    }

    override fun hideUncleLoading() {
        super.hideUncleLoading()
        binding.layoutRefresh.finishRefresh()
    }

    override fun onUncleEvent(event: UncleEventData) {
        super.onUncleEvent(event)
        when(event.eventType){
            UncleEventData.TYPE.UNCLE_PROCESS_REFRESHED -> {//刷新流程完成
                hideUncleLoading()
                presenter!!.checkUncleProcessSteps()
            }
            UncleEventData.TYPE.UNCLE_LOAN_LIMIT_REFRESH -> {//刷新额度
                //首次填写完进件信息，用于显示指引dialog
                presenter!!.requestLimitAmountAction()
            }
            else -> {

            }
        }
    }
}